package com.huabo.controller.business;

import com.huabo.model.User;
import com.huabo.session.DomainModel;
import com.huabo.utils.AjaxUtils;
import com.huabo.utils.ApiUtils;
import com.huabo.utils.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jackie Liu on 2017/3/18.
 */
@Controller
public class ViewController {

    @Autowired
    private DomainModel domainModel;

    @RequestMapping("/view/{dir1}/{dir2}/{page}")
    public String view(@PathVariable("dir1") String dir1, @PathVariable("dir2") String dir2, @PathVariable("page") String page, HttpServletRequest request) {
        if (StringUtils.isEmpty(dir1) || StringUtils.isEmpty(dir2)
                || StringUtils.isEmpty(page)) {
            return "404";
        }
        gainParams(request);
        return dir1 + "/" + dir2 + "/" + page;
    }

    @RequestMapping("/view/{dir}/{page}")
    public String view(@PathVariable("dir") String dir, @PathVariable("page") String page, HttpServletRequest request) {
        if (StringUtils.isEmpty(dir) || StringUtils.isEmpty(page)) {
            return "404";
        }
        gainParams(request);
        return dir + "/" + page;
    }

    @RequestMapping("/{page}")
    public String page(@PathVariable("page") String page, HttpServletRequest request) {
        if (StringUtils.isEmpty(page)) {
            return "404";
        }
        gainParams(request);
        return page;
    }

    private void gainParams(HttpServletRequest request) {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        WebUtils.gainParams(request, paramsMap);
        request.setAttribute("params", paramsMap);

        paramsMap.put("contextPath", domainModel.getWebDomain());

        User user = ApiUtils.getLoginUser(request);
        request.setAttribute("user", user);
    }

    /*//创建一个模版对象
    Template t = new Template(null, new StringReader("用户名：${user};URL：${url};姓名：${name}"), null);
    //创建插值的Map
    Map map = new HashMap();
    map.put("user", "lavasoft");
    map.put("url", "http://www.baidu.com/");
    map.put("name", "百度");
    //执行插值，并输出到指定的输出流中
    t.process(map, new OutputStreamWriter(System.out));*/

    @RequestMapping("/web/keepAlive")
    public void keepAlive(HttpServletRequest request, HttpServletResponse response) {
        AjaxUtils.ajaxJsonSuccessMessage(response, "SUCCESS");
    }
}
